package com.example.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @Description
 * @Author 26233
 * @Create 2021-10-27 21:19:03
 */

public class SelectorServer {

    public static void main(String[] args) throws IOException {
        String hostName = "192.168.101.8";
        int port = 8888;

        Selector selector = Selector.open();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(hostName, port));
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        System.out.println("echo start");
        while (true){
            System.out.println("======================================");
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();
                iterator.remove();
                try{
                    if (selectionKey.isValid()){
                        if (selectionKey.isReadable()){
                            SocketChannel channel = (SocketChannel) selectionKey.channel();
                            ByteBuffer recv = ByteBuffer.allocate(1024);
                            int read = channel.read(recv);

                            System.out.println("read = " + read);
                            ByteBuffer send = ByteBuffer.wrap("echo".getBytes());
                            int write = channel.write(send);
                            System.out.println("write = " + write);

                        }else if (selectionKey.isWritable()){
                            System.out.println("writable");
                        }else if (selectionKey.isAcceptable()){
                            System.out.println("accept");
                            ServerSocketChannel acceptChannel = (ServerSocketChannel) selectionKey.channel();
                            SocketChannel client = acceptChannel.accept();
                            client.configureBlocking(false);
                            client.register(selectionKey.selector(), SelectionKey.OP_READ);

                        }else if (selectionKey.isConnectable()){
                            System.out.println("connect");
                        }
                    }else {
                        System.out.println("select key is invalid");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    selectionKey.channel().close();
                }
            }

        }
    }
}
